import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'package:ball_lion/base/base_controller.dart';
import 'package:ball_lion/module/pick/ai/ai_logic.dart';
import 'package:ball_lion/module/record/record_logic.dart';
import 'package:ball_lion/module/pick/ai/ai_page.dart';
import 'package:ball_lion/module/record/record_page.dart';
import 'package:ball_lion/utils/mode_config.dart';

class DataLogic extends BaseController with GetTickerProviderStateMixin {
  late TabController tabController;
  List<Widget> page = [if (ModeConfig.ai) const AiPage(), const RecordPage()];
  int index = 0;

  @override
  void onInit() {
    tabController = TabController(length: page.length, vsync: this);
    tabController.addListener(() {
      if (tabController.index != index) {
        index = tabController.index;
        update();
      }
    });
    super.onInit();
  }

  Future doRefresh() async {
    if (page[index] is AiPage) {
      Get.find<AiLogic>().doRefresh();
    } else {
      Get.find<RecordLogic>().doRefresh();
    }
  }

  toIndex(int index) {
    tabController.animateTo(index);
  }

  @override
  void getRefresh() {
    page = [if (ModeConfig.ai) const AiPage(), const RecordPage()];
    tabController.dispose();
    tabController = TabController(length: page.length, vsync: this);
    tabController.animateTo(page.length - 1 < index ? 0 : index);
    tabController.addListener(() {
      if (tabController.index != index) {
        index = tabController.index;
        update();
      }
    });
    try {
      Get.find<AiLogic>().getRefresh();
    } catch (e) {
      log("AiLogic not start");
    }
    try {
      Get.find<RecordLogic>().getRefresh();
    } catch (e) {
      log("RecordLogic not start");
    }
    update();
    super.getRefresh();
  }
}
